<?php

namespace Framework\Foundation\Config;

class Config
{
    protected $configData = [];

    public function __construct($config)
    {
        if (is_array($config)) {
            $this->configData = $config;
        } else {
            if (is_string($config)) {
                $this->configData = $this->loadConfig($config);
            }
        }
    }

    public function get($keyChain, $default = null)
    {
        $subConfig = $this->configData;
        for ($i = 1; $i < count($keyChain); $i++) {
            if ('' == $keyChain[$i]) {
                return $subConfig;
            }
            if (!isset($subConfig[$keyChain[$i]])) {
                return $default;
            }
            $subConfig = $subConfig[$keyChain[$i]];
        }
        return $subConfig;
    }

    public function set($keyChain, $value)
    {
        $count = count($keyChain);
        $configSet = &$this->configData;

        for ($i = 1; $i < $count; $i++) {
            $currentKey = array_shift($keys);
            if (!isset($configSet[$currentKey])) {
                $configSet[$currentKey] = $this->processUnIndexKey($keys, $value);
                break;
            } else {
                $configSet = &$configSet[$currentKey];
            }
        }

        return true;
    }

    public function all()
    {
        return $this->configData;
    }

    protected function processUnIndexKey($keys, $value)
    {
        if (empty($keys)) {
            return $value;
        }

        $reversed = array_reverse($keys);
        $data = [];

        $i = 0;
        foreach ($reversed as $k) {
            if ($i == 0) {
                $data[$k] = $value;
                $i++;
                continue;
            }
            $tempData = $data;
            $data = array($k => $tempData);
            $i++;
        }

        return $data;
    }


    /**
     * @param $configFile
     * @return array
     */
    protected function loadConfig($configFile)
    {
//        $file = ROOT . '/app/config/' . $configFile . '.php';
        if (file_exists($configFile)) {
            return include $configFile;
        }

        return [];
    }
}
